//
//  CDVFileOpener.m
//  HelloWorld
//
//  Created by Jing Zhou on 2021/10/14.
//

#import "CDVFileOpener.h"

@interface CDVFileOpener()<UIDocumentInteractionControllerDelegate>
// 缓存文件目录
@property (nonatomic, strong) NSString *downloadDirectory;
@property (nonatomic, strong) UIDocumentInteractionController *documentVC;

@end

@implementation CDVFileOpener



- (void)openFile:(CDVInvokedUrlCommand *)command {
    //这里本地文件直接打开，远程文件就下载然后打开
    NSString *filePath = [command argumentAtIndex:0];
    NSString *token = [command argumentAtIndex:1];
    if ([filePath isEqualToString:@""]) {
        CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR
                                                      messageAsDictionary:@{@"message" : @"invalid file path"}];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
        return;
    }
    
    if ([filePath hasPrefix:@"file://"]) {
        NSString *destinationFilePath = [filePath stringByReplacingOccurrencesOfString:@"file://" withString:@""];
        [self openLocalFilePath:destinationFilePath callbackId:command.callbackId];
    } else {
        [self downloadAndOpenFile:filePath token:token callbackId:command.callbackId];
    }
}

- (void)downloadAndOpenFile:(NSString *)filePath token:(NSString *)token callbackId:(NSString *)callbackId {
    // 1 下载文件
    UIActivityIndicatorView *loadingView = [[UIActivityIndicatorView alloc] init];
    loadingView.center = self.viewController.view.center;
    loadingView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
    loadingView.color = [UIColor grayColor];
    [self.viewController.view addSubview:loadingView];
    [loadingView startAnimating];
    [self.viewController.view setUserInteractionEnabled:NO];
    
    NSURL *sourceURL = [NSURL URLWithString:filePath];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:sourceURL];
    [request addValue:token forHTTPHeaderField:@"X-Auth-Token"];
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithRequest:request completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSString *destinationFilePath = filePath.lastPathComponent;;
        if (!error) {
            //剪切文件
            NSString *fileName = [response.suggestedFilename stringByRemovingPercentEncoding];
            destinationFilePath = [self destinationFileName:fileName];
            [[NSFileManager defaultManager] moveItemAtURL:location toURL:[NSURL fileURLWithPath:destinationFilePath] error:nil];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            // progress 消失
            [loadingView stopAnimating];
            [loadingView removeFromSuperview];
            [self.viewController.view setUserInteractionEnabled:YES];
            if (!error) {
                [self openLocalFilePath:destinationFilePath callbackId:callbackId];
            } else {
                //错误回调
                CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR
                                                              messageAsDictionary:@{@"message" : error.localizedDescription}];
                [self.commandDelegate sendPluginResult:pluginResult callbackId:callbackId];
            }
        });
    }];
    [downloadTask resume];
}

- (void)openLocalFilePath:(NSString *)localFilePath callbackId:(NSString *)callbackId {
    if ([[NSFileManager defaultManager] fileExistsAtPath:localFilePath]) {
        self.documentVC = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:localFilePath]];
        self.documentVC.delegate = self;
        BOOL success = [self.documentVC presentPreviewAnimated:YES];
        if (success) {
            CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK
                                                          messageAsDictionary:@{@"message" : @"successfull openning"}];
            [self.commandDelegate sendPluginResult:pluginResult callbackId:callbackId];
        } else {
            CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR
                                                          messageAsDictionary:@{@"message" : @"can't open file"}];
            [self.commandDelegate sendPluginResult:pluginResult callbackId:callbackId];
        }
    } else {
        //回调失败
        CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR
                                                      messageAsDictionary:@{@"message" : @"file path not exist"}];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:callbackId];
    }
}

- (NSString *)destinationFileName:(NSString *)fileName {
    return [self.downloadDirectory stringByAppendingPathComponent:fileName];
}


- (UIViewController *)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController *)controller {
    return self.viewController;
}

#pragma mark - setter / getter

- (NSString *)downloadDirectory {
    if (!_downloadDirectory) {
        _downloadDirectory = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"DownloadFile"];
        if (![[NSFileManager defaultManager] fileExistsAtPath:_downloadDirectory]) {
            [[NSFileManager defaultManager] createDirectoryAtPath:_downloadDirectory withIntermediateDirectories:YES attributes:nil error:NULL];
        }
    }
    return _downloadDirectory;
}

@end
